﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleTest
{
    class Iterator_Enumerator
    {
        public static void _1_IEnumeratroTest()
        {
            Persons arrPer = new Persons("kewin", "jenny", "chs", "yan");
            foreach (string s in arrPer.GetEnumerable())
            {
                System.Console.WriteLine(s);
            }

            object[] objArr=new object[5];
            objArr[0] = "fddsf";
            foreach (string s in objArr)
            {
                System.Console.WriteLine(s);
            }

            FFOOO temp = new FFOOO();

            foreach (string s in temp.AnIterator())
            {
                System.Console.WriteLine(s);
            }
        }
    }

    public class Persons : System.Collections.IEnumerable
    {
        private class PersonEnumerator : System.Collections.IEnumerator
        {
            private int index = -1;
            private Persons P;
            public PersonEnumerator(Persons p) { this.P = p; }
            public bool MoveNext()
            {
                index++;
                return index < P.m_names.Length;
            }
            public void Reset() { index = -1; }
            public object Current { get { return P.m_names[index];} }
        }

        //获取枚举器
        public System.Collections.IEnumerator GetEnumerator()
        {
           // return new PersonEnumerator(this);
            foreach (string s in m_names)
                yield return s;
        }
        //实现IEnumerable接口的方法
        public System.Collections.Generic.IEnumerable<string> GetGenericEnumerator()
        {
            // return new PersonEnumerator(this);
            foreach (string s in m_names)
                yield return s;
        }

        public System.Collections.IEnumerable GetEnumerable()
        {
            // return new PersonEnumerator(this);
            foreach (string s in m_names)
            {
                //s是一个迭代变量是无法对它进行赋值的，
                //但是可以通过变量的方法，由这些方法修改其内部状态
                //s = s + s;
                

                yield return s;
            }
        }

        string[] m_names;

        public Persons(params string[] names)
        {
            m_names = new string[names.Length];

            names.CopyTo(m_names, 0);
        }

        private string this[int index]
        {
            get
            {
                return
                    m_names[index];
            }
            set
            {
                m_names[index] = value;
            }
        }
    }

    public class FFOOO
    {
        public System.Collections.Generic.IEnumerable<string> AnIterator()
        {
            yield return "str1";
            yield return "str2";
            yield return "str3";
        }
    }
}
